package com.openingedu.mba.util;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * @brief 工具类，包括：封装JSON、解析JSON等
 * @author xiaoyu.wang
 * @date 2012-12-3
 * @version 1.0.0
 * 
 *          Revision History - 2012-12-3: create
 * @param <T>
 ****************************************************************************************/
public class GsonUtil {

	private static GsonBuilder builder = new GsonBuilder();
	private static Gson gson;
	
	static {
		// 不转换没有 @Expose 注解的字段
//		builder.excludeFieldsWithoutExposeAnnotation();
		//Json中的日期表达方式没有办法直接转换成我们的Date类型, 因此需要单独注册一个Date的反序列化类.
		DateDeserializer ds = new DateDeserializer();
		//给GsonBuilder方法单独指定Date类型的反序列化方法
		builder.registerTypeAdapter(Date.class, ds);
		gson = builder.create();
	}

	public static <T> List<T> stl(String json, Type type) {
		return gson.fromJson(json, type);
	}
	
	public static String mts(Map<String, Object> map) throws Exception {
		return gson.toJson(map);
	}

	public static Map<String, Object> stm(String json) throws Exception {
		return gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
	}
	
	public static Gson getGson() {
		return gson;
	}

	public static String otj(Object object) {
		return gson.toJson(object);
	}
	
	/**
	 * 
	 * @param object
	 * @return
	 */
	public static Integer oti(Object object) {
		return gson.fromJson(String.valueOf(object), Integer.class);
	}
	
	/**
	 * 
	 * @param object
	 * @return
	 */
	public static String ots(Object object) {
		return gson.fromJson(String.valueOf(object), String.class);
	}
	
}
